const { pool } = require('../config/db');
const { ValidationError, NotFoundError } = require('../middleware/error');
const ProductModel = require('./product.model');

class CartModel {
  // 获取用户购物车内容
  static async getCart(userId) {
    console.log(`[CartModel.getCart] Called for userId: ${userId}`);
    try {
      const query = `
        SELECT 
          ci.id as cart_item_id,
          ci.product_id,
          ci.quantity,
          ci.added_at,
          ci.updated_at,
          p.name,
          p.slug,
          p.price,
          p.thumbnail_url,
          p.stock_quantity
        FROM cart_items ci
        JOIN products p ON ci.product_id = p.id
        WHERE ci.user_id = ? AND p.is_active = 1
        ORDER BY ci.added_at DESC`;
      console.log(`[CartModel.getCart] Executing query: ${query.replace(/\s+/g, ' ').trim()} with params: [${userId}]`);
      const [items] = await pool.execute(query, [userId]);
      console.log(`[CartModel.getCart] Fetched raw items:`, JSON.stringify(items, null, 2));

      const summary = {
        total_unique_items: items.length,
        total_quantity: items.reduce((sum, item) => sum + item.quantity, 0),
        total_amount: items.reduce((sum, item) => sum + (item.price * item.quantity), 0)
      };

      items.forEach(item => {
        item.subtotal = item.price * item.quantity;
      });

      console.log(`[CartModel.getCart] Returning items:`, JSON.stringify(items, null, 2));
      console.log(`[CartModel.getCart] Returning summary:`, JSON.stringify(summary, null, 2));
      return { items, summary };
    } catch (error) {
      console.error(`[CartModel.getCart] Error for userId: ${userId}:`, error);
      throw error;
    }
  }

  // 添加商品到购物车
  static async addItem(userId, productId, quantity) {
    console.log(`[CartModel.addItem] Called for userId: ${userId}, productId: ${productId}, quantity: ${quantity}`);
    try {
      console.log(`[CartModel.addItem] Checking stock for productId: ${productId}, quantity: ${quantity}`);
      const stockCheck = await ProductModel.checkStock(productId, quantity);
      console.log(`[CartModel.addItem] Stock check result:`, stockCheck);
      if (!stockCheck.available) {
        throw new ValidationError('添加购物车失败', {
          quantity: [`商品库存不足，当前库存: ${stockCheck.current_stock}`]
        });
      }

      const selectExistingQuery = 'SELECT id, quantity FROM cart_items WHERE user_id = ? AND product_id = ?';
      console.log(`[CartModel.addItem] Checking existing item. Query: ${selectExistingQuery} with params: [${userId}, ${productId}]`);
      const [existingItems] = await pool.execute(selectExistingQuery, [userId, productId]);
      console.log(`[CartModel.addItem] Existing items found:`, JSON.stringify(existingItems, null, 2));

      let result;
      let operationType = '';
      if (existingItems.length > 0) {
        operationType = 'UPDATE';
        const existingCartItemId = existingItems[0].id;
        const newQuantity = existingItems[0].quantity + quantity;
        console.log(`[CartModel.addItem] Item exists. cart_item_id: ${existingCartItemId}, current_quantity: ${existingItems[0].quantity}, new_quantity_to_set: ${newQuantity}`);
        
        console.log(`[CartModel.addItem] Re-checking stock for productId: ${productId}, newTotalQuantity: ${newQuantity}`);
        const newStockCheck = await ProductModel.checkStock(productId, newQuantity);
        console.log(`[CartModel.addItem] Re-stock check result:`, newStockCheck);
        if (!newStockCheck.available) {
          throw new ValidationError('添加购物车失败', {
            quantity: [`商品库存不足（购物车中已有该商品），当前库存: ${newStockCheck.current_stock}`]
          });
        }
        
        const updateQuery = 'UPDATE cart_items SET quantity = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?';
        console.log(`[CartModel.addItem] Executing UPDATE. Query: ${updateQuery} with params: [${newQuantity}, ${existingCartItemId}]`);
        [result] = await pool.execute(updateQuery, [newQuantity, existingCartItemId]);
      } else {
        operationType = 'INSERT';
        const insertQuery = 'INSERT INTO cart_items (user_id, product_id, quantity) VALUES (?, ?, ?)';
        console.log(`[CartModel.addItem] Executing INSERT. Query: ${insertQuery} with params: [${userId}, ${productId}, ${quantity}]`);
        [result] = await pool.execute(insertQuery, [userId, productId, quantity]);
      }
      
      console.log(`[CartModel.addItem] ${operationType} result:`, result);

      if (!result || result.affectedRows === 0) {
        console.error(`[CartModel.addItem] ${operationType} failed, affectedRows is 0.`);
        throw new Error('添加购物车失败，数据库操作未影响任何行');
      }

      const selectUpdatedQuery = `SELECT 
          ci.id as cart_item_id,
          ci.product_id,
          ci.quantity,
          ci.added_at,
          ci.updated_at,
          p.name,
          p.price,
          p.thumbnail_url,
          p.stock_quantity
        FROM cart_items ci
        JOIN products p ON ci.product_id = p.id
        WHERE ci.user_id = ? AND ci.product_id = ?`;
      console.log(`[CartModel.addItem] Fetching updated item. Query: ${selectUpdatedQuery.replace(/\s+/g, ' ').trim()} with params: [${userId}, ${productId}]`);
      const [updatedItemRows] = await pool.execute(selectUpdatedQuery, [userId, productId]);
      
      if (!updatedItemRows || updatedItemRows.length === 0) {
        console.error('[CartModel.addItem] Failed to fetch the updated item after insert/update.');
        throw new Error('获取更新后的购物车商品失败');
      }
      const updatedItem = updatedItemRows[0];
      console.log('[CartModel.addItem] Returning updated item:', JSON.stringify(updatedItem, null, 2));
      return updatedItem;
    } catch (error) {
      console.error(`[CartModel.addItem] Error for userId: ${userId}, productId: ${productId}, quantity: ${quantity}:`, error);
      throw error;
    }
  }

  // 更新购物车商品数量
  static async updateItemQuantity(userId, cartItemId, quantity) {
    const [cartItems] = await pool.execute(
      'SELECT product_id FROM cart_items WHERE id = ? AND user_id = ?',
      [cartItemId, userId]
    );

    if (cartItems.length === 0) {
      throw new NotFoundError('购物车商品不存在');
    }

    const stockCheck = await ProductModel.checkStock(cartItems[0].product_id, quantity);
    if (!stockCheck.available) {
      throw new ValidationError('更新数量失败', {
        quantity: [`商品库存不足，当前库存: ${stockCheck.current_stock}`]
      });
    }

    const [result] = await pool.execute(
      'UPDATE cart_items SET quantity = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [quantity, cartItemId]
    );

    if (result.affectedRows === 0) {
      throw new Error('更新购物车失败');
    }

    const [updatedItemRows] = await pool.execute(
      `SELECT 
        ci.id as cart_item_id,
        ci.product_id,
        ci.quantity,
        ci.updated_at,
        p.name,
        p.price,
        p.thumbnail_url,
        p.stock_quantity
      FROM cart_items ci
      JOIN products p ON ci.product_id = p.id
      WHERE ci.id = ?`,
      [cartItemId]
    );
    if (!updatedItemRows || updatedItemRows.length === 0) {
      // Consider if this case needs more specific error handling or logging
      throw new Error('获取更新后的购物车条目失败');
    }
    return updatedItemRows[0];
  }

  // 从购物车中移除商品
  static async removeItem(userId, cartItemId) {
    const [result] = await pool.execute(
      'DELETE FROM cart_items WHERE id = ? AND user_id = ?',
      [cartItemId, userId]
    );

    if (result.affectedRows === 0) {
      throw new NotFoundError('购物车商品不存在');
    }
    return true;
  }

  // 清空购物车
  static async clear(userId) {
    await pool.execute(
      'DELETE FROM cart_items WHERE user_id = ?',
      [userId]
    );
    return true;
  }

  // 验证购物车商品
  static async validateItems(userId) {
    const [items] = await pool.execute(
      `SELECT 
        ci.id as cart_item_id,
        ci.product_id,
        ci.quantity,
        p.name,
        p.stock_quantity,
        p.is_active
      FROM cart_items ci
      JOIN products p ON ci.product_id = p.id
      WHERE ci.user_id = ?`,
      [userId]
    );

    const errors = [];
    for (const item of items) {
      if (!item.is_active) {
        errors.push({
          cart_item_id: item.cart_item_id,
          message: `商品 "${item.name}" 已下架`
        });
        continue;
      }

      if (item.quantity > item.stock_quantity) {
        errors.push({
          cart_item_id: item.cart_item_id,
          message: `商品 "${item.name}" 库存不足，当前库存: ${item.stock_quantity}`
        });
      }
    }

    return {
      valid: errors.length === 0,
      errors
    };
  }
}

module.exports = CartModel; 